package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.utils.FileUploadUtils;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: 孙润达
 * @Date: 2022/1/5 21:02
 */
@RestController
@RequestMapping("/admin/product")
@RefreshScope//扩展配置文件一旦发生变化，马上进行更新
public class FileController {
    //将配置文件里的属性映射
    //@Value("{image.url}")
    private  String imageUrl;
    @Autowired
    private FileUploadUtils fileUploadUtils;
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{
        String path1 = ClassUtils.getDefaultClassLoader().getResource("fdfs_client.conf").getPath();
        //加载配置文件
        ClientGlobal.init(path1);
        //1创建跟踪器
        TrackerClient trackerClient = new TrackerClient();
        //2.连接跟踪器
        TrackerServer connection = trackerClient.getConnection();
        //3.创建服务器的存储节点客户端
        /*
        StorageClient1有两个方法，无参和两参
        * */
        StorageServer storageServer=null;
        StorageClient1 storageClient1 = new StorageClient1(connection, storageServer);
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件的后缀名
        String ext = FilenameUtils.getExtension(fileName);
        //String path = fileUploadUtils.upLoad(file.getOriginalFilename(), file.getBytes());
        //上传图片
        String path = storageClient1.upload_file1(file.getBytes(), ext, null);
        System.out.println("path = " + path);
        System.out.println( imageUrl+ path);
        //return Result.ok("http://101.43.131.40:8080/"+path);
        // 这样地址写死会遇到硬编码问题，地址需要动态获取
        //return  Result.ok(imageUrl+path);
        return  Result.ok("http://101.43.131.40:8080/"+path);
    }
}
